package golink

import (
	"fmt"
	"simqtt-stress/model"
	"simqtt-stress/server/statistics"
	"sync"
	"time"
)

const (
	firstTime    = 1 * time.Second       // 连接以后首次请求数据的时间
	intervalTime = 10 * time.Millisecond // 发送数据的时间间隔
)

// DiffNano 时间差，纳秒
func DiffNano(startTime time.Time) (diff int64) {
	diff = int64(time.Since(startTime))
	return
}
func MqttPub(chanID uint64, ch chan<- *model.RequestResults, totalNumber uint64,
	wg *sync.WaitGroup, request *model.MqttModel) {
	defer func() {
		_ = request.Disconnect()
		wg.Done()
	}()

	var (
		i uint64
	)
	// 暂停60秒
	t := time.NewTimer(firstTime)
	for {
		if i == 0 {
			<-t.C
		}
		time.Sleep(20 * time.Millisecond)
		var (
			startTime = time.Now()
			isSucceed = true
			cc        = make(chan struct{}, 1)
			errCode   = model.HTTPOk
		)
		// 请求
		e := request.Publish(cc)
		if e != nil {
			fmt.Println(e)
		} else {
			select {
			case <-cc:
			case <-time.After(time.Millisecond * 500):
				e = fmt.Errorf("timeout publish waiting ack")
			}
		}
		requestTime := uint64(DiffNano(startTime))
		statistics.RequestTimeList = append(statistics.RequestTimeList, requestTime)
		if e != nil && e.Error() == "timeout publish waiting ack" {
			isSucceed = false
			errCode = model.RequestErr
		} else if e != nil {
			isSucceed = false
			errCode = model.PubTimeout
		}
		requestResults := &model.RequestResults{
			Time:      requestTime,
			IsSucceed: isSucceed,
			ErrCode:   errCode,
		}
		requestResults.SetID(chanID, i)
		ch <- requestResults
		// 结束条件
		i++
		if i >= totalNumber {
			goto end
		}
	}
end:
	t.Stop()
}
func MqttSub(chanID uint64, ch chan<- *model.RequestResults, totalNumber uint64,
	wg *sync.WaitGroup, request *model.MqttModel) {
	defer func() {
		wg.Done()
	}()
	defer func() {
		// _ = request.UnSubTopic()
		_ = request.Disconnect()
	}()

	var (
		i uint64
	)
	// 暂停60秒
	t := time.NewTimer(firstTime)

	for {
		select {
		case <-t.C:
			t.Reset(intervalTime)

			var (
				startTime = time.Now()
				isSucceed = true
				errCode   = model.HTTPOk
				cc        = make(chan struct{}, 1)
			)
			// 请求
			e := request.SubTopic(cc)
			select {
			case <-cc:
			case <-time.After(time.Millisecond * 400):
				e = fmt.Errorf("timeout sub waiting ack")
			}
			requestTime := uint64(DiffNano(startTime))
			statistics.RequestTimeList = append(statistics.RequestTimeList, requestTime)
			if e != nil {
				isSucceed = true
				errCode = model.RequestErr
			}
			requestResults := &model.RequestResults{
				Time:      requestTime,
				IsSucceed: isSucceed,
				ErrCode:   errCode,
			}
			requestResults.SetID(chanID, i)
			ch <- requestResults

			// 结束条件
			i = i + 1
			if i >= totalNumber {
				goto end
			}
		}
	}
end:
	t.Stop()
}
